package org.jash.shop2112.category

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.shop2112.entity.Category
import org.jash.shop2112.entity.Goods
import org.jash.shop2112.mvvm.BaseViewModel

class CategoryViewModel:BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<List<Goods>>() }
    val categoryLiveData by lazy { MutableLiveData<List<Category>>() }
    fun loadGoods(cid:Int, page:Int, size:Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoods(cid, page, size)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
    fun loadCategory() {
        viewModelScope.launch {
            try {
                val res = service.getCategory()
                if (res.code == 200) {
                    categoryLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
}